/**
 * 处理各报表私有的逻辑
 * 通过id获取
 *
 * 目前配置包括
 * [reportId]: {
 *     // 生成searchForm时对对应筛选器进行特殊处理，一定要同步
 *     // 本来是支持生成searchForm时异步处理的，后来思考了很久删掉了支持的代码
 *     // 就两个原因：麻烦，非常影响用户体验
 *     searchItemHandler: {
 *         [criteriaCode]: ({context, code, name}) => {
 *             return {}  // 必须返回一个筛选器对象
 *         }
 *     },
 *
 *     // searchItem的初始值，参考searchFormInitialValueFactory,
 *     searchItemInitialValue: any,
 *
 *     // searchItem的初始值，与searchItemInitialValue不同的是通过name去匹配,
 *     // 最开始犹豫了很久要不要加这个东西，因为我很想把这里面既基于code又基于name去处理的逻辑干掉
 *     // 但是最终发现，似乎不太可能，而且有的地方还是需要用name去匹配处理
 *     // 只能说后端在设计这一块的时候可能就有些问题
 *     // 另外：与searchItemInitialValue同时使用会造成覆盖！！！！
 *     searchItemInitialValueByName: any,
 *
 *     // 处理列数据，返回一个新列
 *     columnsHandler: ({list, context}) => {
 *         return []
 *     }
 *
 *     // 同universal-report.service.js中的validateCodeMap
 *     validateCodeMap: {
 *         [criteriaCode]: ({value, params, label}) => {
 *             return err
 *         }
 *     },
 *     // 同universal-report.service.validateNameMap
 *     validateNameMap: {
 *         [criteriaPropName]: ({value, params, label}) => {
 *             return err
 *         }
 *     },
 *
 *     // 渲染在表格和搜索条件中间的内容
 *     // 为什么只支持渲染在表格和搜索条件中间？
 *     // 因为advancedTable目前只支持这么渲染
 *     // 我又懒得再去在下面加其他东西，如果后续有需求麻烦开发考虑一下通用性
 *     renderChildren: (context) => <div></div>
 *
 *     // 返回一个函数集合，用于方便renderChildren调用
 *     methodCollectionFactory: (context) => {
 *         return {
 *             [methodName]: () => {}
 *         }
 *     },
 *
 *     // 私用报表的state
 *     reportPrivateState: {},
 *
 *     // 搜索时额外调用方法
 *     extraSearch: ({params, context}) => {}
 *
 *     // 是否在初始化结束之后就搜索
 *     initSearch: boolean
 *
 * }
 *
 */
import { currentTime, currentTimeBeforeThree, checkDateDuration } from "./universal-report.service";
import UniversalReportService from "./universal-report.service";
import { messages } from "share/common";
import { Icon, Popover } from "antd";
import React from "react";
import menuRoute from "routes/menuRoute";

const EXPENSE_CLAIM_REPORT = '6';  // 报销单报表
const INVOICE_SUMMARY_REPORT = '15'; // 发票汇总报表
const APPROVE_EFFICIENCY_REPORT = '12';  // 审批效率报表
const APPROVE_EFFICIENCY_DETAIL_REPORT = '13';  // 审批效率明细报表
const WAIT_APPROVE_EFFICIENCY_REPORT = '33';  // 待审批效率报表
const EFFICIENCY_REPORT = '4';  // 效率报表
const BUSINESS_CARD_REPORT = '9';  // 商务卡报表
const PAYMENT_DETAIL_REPORT = '40';  // 付款明细报表
const APPORTIONMENT_REPORT = '14';  // 分摊报表
const EXPENSE_DETAIL_REPORT = '3';  // 费用明细报表
const TRAVEL_SUMMARY_REPORT = '1'; // 打车出行汇总报表
const LOAN_REPORT = '7'; //借款报表
const LOAN_PAYBACK_REPORT = '19'; //还款报表

function dateValidate(values) {
  let [start, end] = values;
  if (!start && !end) {
    return {
      requiredError: true
    }
  } else {
    if (checkDateDuration(start, end)) {
      return {
        durationError: true
      }
    }
  }
  return {}
}

/**
 * 统一校验日期
 * @param params  校验对象
 * @param array 需要校验的日期name数组
 * @param requiredString 未填写任何日期时返回返回值，如果不传值则表示不强制必填
 * @returns {*}
 */
function datesValidate(params, array, requiredString = '') {
  let requiredSuccess = false;
  let durationSuccess = true;
  // console.log('datesValidate params', params, array);
  let valuedParams = params && Object.keys(params).filter(item => {
    let value = params[item];
    let type = typeof value;
    if (value === null) return false;
    if (type === 'undefined') return false;
    if (type === 'string') return true;
    if (type === 'object') {
      let isArray= false
      if(Array.isArray(value)){
        isArray= true
        value= value.filter(item=>item != null)
      }
      if (item === 'label_types') {
        if (value && value.selectedLabels && value.selectedLabels.length > 0) return true;
      } else if (item === 'set_of_books_id') {
        return false;
      } else if(isArray && value.length === 0 || (value && Object.keys(value).length === 0)){
        return false
      } else if (item === 'receipt_label_types') {
        if (value && value.receipt_label_types) return true
      } else {
        return true;
      }
    }
    return false;
  }) || [];
  // console.log('valuedParams', valuedParams);
  if (valuedParams && valuedParams.length > 0) return false;
  array.forEach(key => {
    let dateItem = params[key] || [];
    const { requiredError, durationError } = dateValidate(dateItem);
    if (!requiredError) { // 只要有一个日期填了则不提示必填
      requiredSuccess = true;
    }
    if (durationError) {  // 只要有一个日期跨度超过12个月则提示
      durationSuccess = false;
    }
  });

  if (!requiredSuccess) {
    return requiredString
  }
  if (!durationSuccess) {
    return messages('finance-7.key269')/*查询时间跨度不能超过12个月*/
  }
}

export default {
  [INVOICE_SUMMARY_REPORT]: {
    searchItemInitialValueByName: {
      'expense_created_date': ({context}) => {
        const { extraParams } = context.state;
        const { expense_created_date } = extraParams;
        if (expense_created_date && expense_created_date.length) {
          return expense_created_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    },
    validateNameMap: {
      'receipt_date': ({ value, params }) => {
        const validateArray = ['receipt_date', 'reimb_audit_approval_date', 'reimb_submitted_date', 'expense_created_date',
          'reimb_payment_date', 'reimb_book_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      }
    }
  },
  [APPROVE_EFFICIENCY_REPORT]: {
    reportPrivateState: {
      cardData: {},
    },
    methodCollectionFactory(context) {
      return {
        rowDetail: (e, record) => {
          let { approverOid, approver } = record;
          let { advancedTableRef } = context;
          const { extraParams = {} } = context.state;
          const { currentRoute } = context.props;
          let values = advancedTableRef.getFieldsValue();
          for (let key in values) {
            extraParams[key] = values[key];
          }
          // 保存当前extraParams之后进行页面跳转（这里的页面跳转是当前页面跳当前页面）
          extraParams.approverOid = approverOid;
          extraParams.approver = approver;
          context.setState({
            extraParams
          }, () => {
            //这边跳转到当前页面，路由id变为 13，查询一样的条件，把审批人，oid带入查询条件
            let path = menuRoute.getRouteItem(currentRoute, 'key').url.replace(':id', 13);
            context.context.router.push(path);
          });
        }
      }
    },
    columnsHandler: ({ context, list }) => {
      let { methodCollection = {} } = context.state;
      if (list.length) {
        list.push({
          fixed: 'right',
          width: 100,
          title: messages('common.operation')/*操作*/,
          render: (text, record) => (<span>
              <a onClick={(e) => methodCollection.rowDetail(e, record)}>
                {messages('common.detail')/*详情*/}
              </a>
            </span>)
        })
      }
      return list
    },
    extraSearch: ({ requestBody, context }) => {
      UniversalReportService.getApproverTime(requestBody)
        .then((res) => {
          const { reportPrivateState } = context.state;
          reportPrivateState.cardData = res.data;
          context.setState({
            reportPrivateState
          })
        })
    },
    renderChildren: (context) => {
      const { reportPrivateState } = context.state;
      const { cardData = {} } = reportPrivateState;
      return (<div className='card-ward'>
        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('finance-7.key282')/*处理单据数量*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.processedNumber}</h2>
          </div>
        </div>

        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('finance-7.key283')/*审批节点平均时长*/}
            </div>
            <div className='tips f_right'>
              <Popover content={messages('finance-7.key284')/*自动审批节点不纳入数据统计*/}>
                <Icon type="info-circle"/>
              </Popover>
            </div>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.documentAverageApprovalTime}</h2>
          </div>
        </div>

        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('finance-7.key285')/*流程平均审批节点数*/}
            </div>
            <div className='tips f_right'>
              <Popover content={messages('finance-7.key284')/*自动审批节点不纳入数据统计*/}>
                <Icon type="info-circle"/>
              </Popover>
            </div>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.averageNodeNumber}</h2>
          </div>
        </div>

        <div className='card-item last-card-item'>
          <div className='header'>
            <div className='title f_left'> {messages('finance-7.key286')/*审批流程平均时长*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.averageApprovalTime}</h2>
          </div>
        </div>
      </div>)
    },
  },
  [APPROVE_EFFICIENCY_DETAIL_REPORT]: { // 审批效率明细报表
    initSearch: true,
    searchItemInitialValueByName: {
      'approval_time': ({context}) => {
        const { extraParams } = context.state;
        const { approval_time } = extraParams;
        if (approval_time && approval_time.length) {
          return approval_time
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
      'company_oid': ({context}) => {
        const { extraParams } = context.state;
        const { company_oid } = extraParams;
        if (company_oid) {
          return company_oid
        } else {
          return undefined
        }
      },
      'department_code': ({context}) => {
        const { extraParams } = context.state;
        const { department_code } = extraParams;
        if (department_code) {
          return department_code
        } else {
          return undefined
        }
      },
      'approver_oid': ({context}) => {
        const { extraParams } = context.state;
        const { approverOid: userOID, approver: fullName } = extraParams;
        if (userOID) {
          return [{
            userOID,
            fullName
          }]
        } else {
          return undefined
        }
      },
      'approver_duty_code': ({context}) => {
        const { extraParams } = context.state;
        const { approver_duty_code } = extraParams;
        if (approver_duty_code) {
          return approver_duty_code
        } else {
          return undefined
        }
      },
      'approver_title': ({context}) => {
        const { extraParams } = context.state;
        const { approver_title } = extraParams;
        if (approver_title) {
          return approver_title
        } else {
          return undefined
        }
      },
    }
  },
  [WAIT_APPROVE_EFFICIENCY_REPORT]: {
    reportPrivateState: {
      cardData: {}
    },
    extraSearch: ({ requestBody, context }) => {
      UniversalReportService.getWaitingTime(requestBody)
        .then((res) => {
          const { reportPrivateState } = context.state;
          reportPrivateState.cardData = res.data;
          context.setState({
            reportPrivateState
          })
        })
    },
    renderChildren: (context) => {
      const { reportPrivateState } = context.state;
      const { cardData = {} } = reportPrivateState;

      return (<div className='card-ward'>
        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'>
              {messages('finance-7.key287')/*待审批单据数量*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.allApprovedDocTodoQty}</h2>
          </div>
        </div>
        <div className='card-item'>
          <div className='header'>
            <div className='title f_left'>
              {messages('finance-7.key288')/*平均待审批时长*/}
            </div>
            <div className='tips f_right'/>
          </div>
          <div className="content">
            <h2 className='card-content'>{cardData.averageApprovalTodoTime}</h2>
          </div>
        </div>
      </div>)
    },
  },
  [EXPENSE_CLAIM_REPORT]: {
    validateNameMap: {
      'submitted_date': ({ value, params }) => {
        const validateArray = ['submitted_date', 'reimb_audit_approval_date', 'receive_date',
          'reimb_real_payment_date', 'reimb_book_date', 'approval_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'submitted_date': ({context}) => {
        const { extraParams } = context.state;
        const { submitted_date } = extraParams;
        if (submitted_date && submitted_date.length) {
          return submitted_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [LOAN_REPORT]: {
    validateNameMap: {
      'app_submitted_by_date': ({ value, params }) => {
        const validateArray = ['app_submitted_by_date', 'final_approval_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key316')/*请选择提交日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'app_submitted_by_date': ({context}) => {
        const { extraParams } = context.state;
        const { app_submitted_by_date } = extraParams;
        if (app_submitted_by_date && app_submitted_by_date.length) {
          return app_submitted_by_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [LOAN_PAYBACK_REPORT]: {
    validateNameMap: {
      'submitted_date': ({ value, params }) => {
        const validateArray = ['submitted_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key317')/*请选择还款单提交日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'submitted_date': ({context}) => {
        const { extraParams } = context.state;
        const { submitted_date } = extraParams;
        if (submitted_date && submitted_date.length) {
          return submitted_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [EFFICIENCY_REPORT]: {
    validateNameMap: {
      'reimb_submitted_date': ({ value, params }) => {
        const validateArray = ['reimb_submitted_date', 'reimb_approval_date', 'reimb_receive_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'reimb_submitted_date': ({context}) => {
        const { extraParams } = context.state;
        const { reimb_submitted_date } = extraParams;
        if (reimb_submitted_date && reimb_submitted_date.length) {
          return reimb_submitted_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [BUSINESS_CARD_REPORT]: {
    validateNameMap: {
      'trs_datetime': ({ value, params }) => {
        const validateArray = ['trs_datetime', 'reimb_audit_approval_date', 'pos_datetime'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'trs_datetime': ({context}) => {
        const { extraParams } = context.state;
        const { trs_datetime } = extraParams;
        if (trs_datetime && trs_datetime.length) {
          return trs_datetime
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [PAYMENT_DETAIL_REPORT]: {
    validateNameMap: {
      'created_date': ({ value, params }) => {
        const validateArray = ['created_date', 'pay_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key303')/*请选择创建时间*/);
        if (error) return error;
      },
    }
  },
  [APPORTIONMENT_REPORT]: {
    validateNameMap: {
      'expense_created_date': ({ value, params }) => {
        const validateArray = ['expense_created_date', 'reimb_submitted_date', 'reimb_audit_approval_date',
          'reimb_payment_date', 'reimb_book_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'expense_created_date': ({context}) => {
        const { extraParams } = context.state;
        const { expense_created_date } = extraParams;
        if (expense_created_date && expense_created_date.length) {
          return expense_created_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  },
  [EXPENSE_DETAIL_REPORT]: {
    validateNameMap: {
      'expense_created_date': ({ value, params }) => {
        const validateArray = ['expense_created_date', 'reimb_submitted_date', 'reimb_audit_approval_date', 'reimb_payment_date'];
        let error = datesValidate(params, validateArray);
        if (error) return error;
      },
    }
  },
  [TRAVEL_SUMMARY_REPORT]: {
    validateNameMap: {
      'reimb_audit_approval_date': ({ value, params }) => {
        const validateArray = ['leave_on', 'reimb_audit_approval_date'];
        let error = datesValidate(params, validateArray, messages('finance-7.key302')/*请选择日期*/);
        if (error) return error;
      },
    },
    searchItemInitialValueByName: {
      'reimb_audit_approval_date': ({context}) => {
        const { extraParams } = context.state;
        const { reimb_audit_approval_date } = extraParams;
        if (reimb_audit_approval_date && reimb_audit_approval_date.length) {
          return reimb_audit_approval_date
        } else {
          return [currentTimeBeforeThree, currentTime]
        }
      },
    }
  }
}
